package bot.controller;

import bot.pojo.Addition;
import bot.pojo.Ai;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.net.URL;
@RestController
@RequestMapping("/Ai")
public class aiPicturesController {

    @GetMapping("/aiPictures")
    public Object aiPictures(String text) throws InterruptedException, IOException {
        Addition addition = new Addition();
        Ai ai = new Ai();
        ai.setAddition(addition);
        ai.setContent(text);
        String s = JSONObject.toJSONString(ai);
        String URL = "https://x.6pen.art/api/v2/fantasy/submit-task";
        Map head = new HashMap();
        head.put("mbd-t","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo0NTM1OTIxLCJleHBpcmVkX2F0IjoxNjkyNzczODk2fQ.DEK8a9EMR9LiqF24Af8PYmSUsj0xzbLOpOja5g_-qPU");
        //String s1 = HttpHelp.sendGetRequest(URL, head);
        String s1 = bot.pojo.HttpHelp.sendPostJson(URL, s,head );

        Ai aiData = JSONObject.parseObject(s1, Ai.class);
        Thread.sleep(15000);
        String URL2 = "https://x.6pen.art/api/v2/fantasy/task/"+aiData.getData().getTask_id();
        String s2 = HttpHelp.sendGetRequest(URL2, head);
        Ai ImgData = JSONObject.parseObject(s2, Ai.class);
        if(ImgData.getData().getResult() == null){//如果20秒内没有出结果就再等待10秒后访问
            Thread.sleep(10000);
            s2 = HttpHelp.sendGetRequest(URL2, head);
            ImgData = JSONObject.parseObject(s2, Ai.class);
        }
        String result = ImgData.getData().getResult();

        java.net.URL url = new URL(result);
        URLConnection conn = url.openConnection();
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int length;
        while ((length = in.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
        byte[] imageBytes = out.toByteArray();
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
        long l = System.currentTimeMillis();
        String timeStr = String.valueOf(l);

        String filePath = "/home/bot/AiImage/"+timeStr+".jpg";
        File outputfile = new File(filePath);
        ImageIO.write(image, "jpg", outputfile);

        return filePath;
    }
}
